<template>
	<view class="connect" :style="{ paddingTop: paddingHeight + 'px' }">
		<nav-bar></nav-bar>
		<view class="title mt"> 坐直并放轻松 </view>
		<view class="tip"> 我们将向您介绍并引导您完成测量 </view>
		<image
			:style="{
				width: windowHeight < 800 ? '600rpx' : '750rpx',
				height: windowHeight < 800 ? '600rpx' : '750rpx'
			}"
			src="http://oss.antaimedical.com/images/pro/2025/02/67ab17ece4b0d615350f3134e8JytKyMPo5e70dc98cdb4361457a48bf11f7d7701ff.png"
			class="start"
		/>
		<view
			class="continue"
			v-if="connectSatus"
			@click="$u.throttle(checkTimePop, 1500)"
		>
			开始
		</view>
		<view v-else>
			<view class="loading-d" v-if="showLoading">
				<u-loading-icon size="18" :show="true"></u-loading-icon>
				<text class="l-t">开启您的仪器</text>
			</view>
			<view class="not" v-if="showLoading"> 不能连接仪器? </view>
			<view class="connect" v-else @click="$u.throttle(connect, 1500)">
				连接仪器
			</view>
		</view>
		<u-popup
			:show="showPop"
			mode="bottom"
			:closeOnClickOverlay="true"
			round="12"
			@close="showPop = false"
		>
			<view class="myDevice">
				<view class="line"></view>
				<view class="divece_name"> {{ userInfo.name }}的代谢仪 </view>
				<image
					src="http://oss.antaimedical.com/images/static/2024/05/664f09e6eb14d0f049f44cebLDZqXrRZgSqe11d91b357b29d490d4ba152491082d97.png"
					class="device_img"
				/>
				<view class="battery">
					<text class="info" v-if="ble.defaultInfo.battery"
						>{{ ble.defaultInfo.battery }}%</text
					>
					<u-loading-icon
						v-else
						size="18"
						:show="true"
					></u-loading-icon>
					<u-image
						width="44rpx"
						height="26rpx"
						:showMenuByLongpress="false"
						:src="myGetBatteryIcon(ble.defaultInfo.battery)"
						:showLoading="false"
						:showError="false"
						:lazy-load="true"
					></u-image>
				</view>
				<view
					v-if="connectSatus"
					class="continue"
					@click="$u.throttle(checkTimePop, 1500)"
					style="margin-top: 20rpx"
				>
					开始
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
import {
	getDeviceByUser,
	findMeasureRerPopup,
	getDetailsByUser
} from '@/api/index.js'
import { hex2int, hexToString, getBatteryIcon } from '@/utils/utils.js'
import { mapState, mapGetters } from 'vuex'
const BLE = require('@/utils/ble.js')
export default {
	data() {
		return {
			paddingHeight: uni.getStorageSync('navbarHeight'),
			userId: uni.getStorageSync('userId'),
			imgUrl: this.$imgUrl,
			windowHeight: uni.$u.sys().windowHeight,
			defaultDev: {},
			differentTime: undefined,
			exhaleMeasure: false, // 是否测量呼气量
			showLoading: false,
			showPop: false, // 连接成功弹框提示
			upgradeInfo: undefined,
			connectSatus: false,
			timeout: undefined, // 倒计时函数
			parameter: {
				tag: null,
				sportId: null,
				meal: null,
				recordId: null
			},
			userInfo: {}
		}
	},
	computed: {
		...mapState({
			ble: (state) => state.ble // 实时蓝牙全局状态
		})
	},
	watch: {
		'ble.defaultInfo.battery': {
			handler(newVal, oldVal) {
				if (newVal) {
					this.showPop = true
					this.connectSatus = true
				}
			}
		},
		'ble.state': {
			handler(newVal, oldVal) {
				if (newVal == -5) {
					this.showLoading = false
					uni.showToast({
						title: '连接超时',
						icon: 'error'
					})
				} else if (newVal == 0) {
					// this.showPop = true
					// this.connectSatus = true
				}
			}
		}
	},
	async onLoad(OPTIONS) {
		let that = this
		await this.getInfoByUser()
		if (this.userInfo.maxExhale < 1 && OPTIONS.type != 'updateExhale') {
			this.exhaleMeasure = true
			uni.showModal({
				title: '提示',
				content: '检测到您未测量肺活量，先测量肺活量',
				confirmColor: '#1F2434',
				showCancel: false,
				// cancelText: '再看看',
				confirmText: '确定',
				success(res) {
					that.fetchDeviceData()
				}
			})
		} else {
			if (OPTIONS.type != 'updateExhale') {
				this.parameter.tag = OPTIONS.tag
				this.parameter.sportId = OPTIONS.sportId
				this.parameter.meal = OPTIONS.meal
				this.parameter.recordId = OPTIONS.recordId
				this.exhaleMeasure = false
			} else {
				this.exhaleMeasure = true
			}
			this.fetchDeviceData()
		}
	},
	onShow() {},
	onHide() {},
	onUnload() {
		clearTimeout(this.timeout)
		wx.offBluetoothAdapterStateChange()
		if (this.ble.state == -2) {
			wx.stopBluetoothDevicesDiscovery()
		}
	},
	methods: {
		// 更新用户的肺活量信息
		async getInfoByUser() {
			let params = {
				userId: this.userId,
				urlencoded: true
			}
			await getDetailsByUser(params).then((res) => {
				this.userInfo = res.data
				this.$store.commit('setUserInfo', res.data)
			})
		},
		connect() {
			this.fetchDeviceData()
		},
		checkBleStatus() {
			let that = this
			if (this.ble.isOpenBleAdapter) {
				wx.getBluetoothAdapterState({
					success: (res) => {
						if (!res.available) {
							uni.showModal({
								title: '提示',
								content:
									'检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
								showCancel: false,
								confirmColor: '#545DDE',
								success(b_res) {
									if (b_res.confirm) {
										that.timeout = setTimeout(() => {
											wx.offBluetoothAdapterStateChange()
											if (that.ble.state != 0) {
												that.showLoading = false
												that.connectSatus = false
											}
										}, 15000)
										wx.onBluetoothAdapterStateChange(
											function (res) {
												if (res.available) {
													wx.offBluetoothAdapterStateChange()
													that.connectDev()
													clearTimeout(that.timeout)
												}
											}
										)
									}
								}
							})
						} else {
							that.connectDev()
						}
					},
					fail: (err) => {
						uni.showModal({
							title: '提示',
							content: '请检查蓝牙功能是否正常',
							showCancel: false
						})
					}
				})
			} else {
				wx.closeBluetoothAdapter()
				wx.openBluetoothAdapter({
					success(BleObj) {
						that.$store.commit('changeIsOpenBleAdapter', true)
						that.connectDev()
					},
					fail(err) {
						console.log('openBluetoothAdapter', err)
						if (err.errCode == 10001) {
							that.$store.commit('changeIsOpenBleAdapter', true)
							uni.showModal({
								title: '提示',
								content:
									'检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
								showCancel: false,
								confirmColor: '#545DDE',
								success(b_res) {
									if (b_res.confirm) {
										that.timeout = setTimeout(() => {
											wx.offBluetoothAdapterStateChange()
											if (that.ble.state != 0) {
												that.showLoading = false
												that.connectSatus = false
											}
										}, 15000)
										wx.onBluetoothAdapterStateChange(
											function (res) {
												if (res.available) {
													wx.offBluetoothAdapterStateChange()
													that.connectDev()
													clearTimeout(that.timeout)
												}
											}
										)
									}
								}
							})
						}
						if (
							err.errMsg == 'openBluetoothAdapter:fail auth deny'
						) {
							uni.showModal({
								title: '提示',
								content: '请先授权蓝牙权限',
								confirmColor: '#545DDE',
								success(modal_res) {
									if (modal_res.confirm) {
										wx.openSetting({
											success: (authData) => {
												if (
													authData.authSetting[
														'scope.bluetooth'
													]
												) {
													that.checkBleStatus()
												} else {
													// 未授权
													uni.showModal({
														title: '提示',
														content:
															'授权失败,您将无法使用蓝牙相关服务',
														confirmColor: '#545DDE',
														showCancel: false,
														success(modal) {
															if (modal.confirm) {
																wx.closeBluetoothAdapter()
																that.$store.commit(
																	'changeIsOpenBleAdapter',
																	false
																)
															}
														}
													})
												}
											}
										})
									} else {
										uni.showModal({
											title: '提示',
											content:
												'授权失败,您将无法使用蓝牙相关服务',
											confirmColor: '#545DDE',
											showCancel: false,
											success(modal) {
												if (modal.confirm) {
													wx.closeBluetoothAdapter()
													that.$store.commit(
														'changeIsOpenBleAdapter',
														false
													)
												}
											}
										})
									}
								}
							})
						}
					}
				})
			}
		},
		// 连接仪器
		connectDev() {
			if (uni.$u.os() == 'android') {
				// 安卓系统直接连接
				this.$store.commit('setDefaultInfo', {
					type: 1,
					data: {
						mac: this.defaultDev.deviceMac,
						name: this.defaultDev.bluetoothName
					}
				})
				BLE.common.createBLEConnectionFn(
					this.defaultDev.deviceMac,
					this.defaultDev
				)
			} else {
				// 苹果系统需要搜索uuid仪器id
				BLE.common.myStartBluetoothDevicesDiscovery(
					10000,
					this.defaultDev
				)
			}
		},

		// 获取已绑定仪器信息
		async fetchDeviceData(info) {
			let params = {
				userId: this.userId,
				urlencoded: true
			}
			try {
				const res = await getDeviceByUser(params)
				if (res.code == 200) {
					if (res.data.length) {
						this.defaultDev = res.data.find((item) => {
							return item.isDefault == 1
						})
						this.$store.commit('setDeviceInfo', this.defaultDev)
						if (this.ble.state == 0) {
							// 判断此时蓝牙是否处于连接状态
							this.showPop = true
							this.connectSatus = true
						} else if (this.ble.state < 0) {
							this.showLoading = true
							this.connectSatus = false
							this.checkBleStatus()
						}
					} else {
						uni.navigateTo({
							url: '/pagesA/device/search/index?type=connect'
						})
					}
				}
			} catch (e) {
				//TODO handle the exception
			}
		},
		async checkTimePop() {
			let params = {
				userId: this.userId
			}
			try {
				const res = await findMeasureRerPopup(params)
				if (res.code == 200 && res.data == 1) {
					uni.showModal({
						title: '提示',
						content: '检测到相邻2次测量间隔<2min，会影响测量结果',
						showCancel: false,
						success: (modal) => {
							if (modal.confirm) {
								if (this.exhaleMeasure) {
									// 是否测量呼气量
									uni.redirectTo({
										url: `/pagesB/login/device/measure/exhale?type=update`
									})
								} else {
									uni.redirectTo({
										url: `/pagesA/health/device/measure/prepare?params=${JSON.stringify(
											this.parameter
										)}`
									})
								}
							}
						}
					})
				} else {
					if (this.exhaleMeasure) {
						// 是否测量呼气量
						uni.redirectTo({
							url: `/pagesB/login/device/measure/exhale?type=update`
						})
					} else {
						uni.redirectTo({
							url: `/pagesA/health/device/measure/prepare?params=${JSON.stringify(
								this.parameter
							)}`
						})
					}
				}
			} catch (e) {
				//TODO handle the exception
			}
		},
		myGetBatteryIcon(data) {
			return getBatteryIcon(data)
		}
	}
}
</script>
<style lang="scss" scoped>
.connect {
	display: flex;
	flex-direction: column;
	align-items: center;

	.title {
		margin-top: 146rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 36rpx;
		color: #1f2434;
	}

	.tip {
		margin-top: 16rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 28rpx;
		color: rgba(31, 36, 52, 0.5);
		line-height: 46rpx;
	}

	.loading-d {
		margin: 148rpx 0 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;

		.l-t {
			padding-left: 16rpx;
			font-size: 32rpx;
			font-weight: 500;
			color: #333333;
		}
	}

	.connect,
	.not {
		width: 100%;
		text-align: center;
		text-decoration: underline;
		color: #545dde;
		font-size: 32rpx;
		padding-left: 53rpx;
	}

	.connect {
		margin-top: 148rpx;
		padding-left: 0;
	}

	.myDevice {
		padding: 40rpx 0 60rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

		.line {
			width: 136rpx;
			height: 10rpx;
			background: #666666;
			border-radius: 5rpx;
		}

		.divece_name {
			padding: 80rpx 0 96rpx;
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
		}

		.device_img {
			width: 116rpx;
			height: 310rpx;
		}

		.battery {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 64rpx;
			margin-left: 8rpx;

			.info {
				font-size: 24rpx;
				color: #666666;
				padding-right: 10rpx;
			}
		}
	}

	.continue {
		margin-top: 156rpx;
		width: 423rpx;
		height: 86rpx;
		background: #1f2434;
        display: flex; 
        justify-content: center;
        align-items: center;
        color: #fff;
        border-radius: 64rpx;
        font-size: 28rpx;
	}
}
</style>
